<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        body {
            height: 100vh;
            overflow: hidden;
        }
        #demo {
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            margin: auto;
            /*background: pink;*/
        }
    </style>
</head>
<body>
<canvas id="demo"></canvas>
<script>
    var canvas = document.getElementById("demo");
    if (canvas.getContext){
        var ctx = canvas.getContext("2d");
        var img = new Image();
        img.src = "renwu.webp";
        img.onload = function (){
            canvas.width = img.width*2;
            canvas.height = img.height;
            draw();
        }
        function draw(){
            ctx.drawImage(img,0,0)

            var oldimgdata =ctx.getImageData(0,0,img.width,img.height);
            var newimgdata = ctx.createImageData(img.width,img.height);
            //马赛克
            // 选取一个马赛克矩形
            var size = 5;
            // 将马赛克矩形中随机抽出一个像素点的信息(rgba)
             for (var i = 0;i<oldimgdata.width/size;i++){
                 for (var j = 0;j<oldimgdata.height/size;j++){
                    var color = getPxInfo(oldimgdata,i*size+Math.floor(Math.random()*size),j*size+Math.floor(Math.random()*size));
                    for (var a=0;a<size;a++){
                        for (var b = 0;b<size;b++){
                            setPxInfo(newimgdata,i*size+a,j*size+b,color)
                        }
                    }
                 }
             }
            ctx.putImageData(newimgdata,img.width,0)


        }

        // 将整个马赛克矩形中的像素点信息统一调成随机的那个
        function getPxInfo(imgdata,x,y){
            var color = [];
            var data = imgdata.data;
            var w = imgdata.width;
            var h = imgdata.height;

            color[0]=data[(y*w+x)*4];
            color[1]=data[(y*w+x)*4+1];
            color[2]=data[(y*w+x)*4+2];
            color[3]=data[(y*w+x)*4+3];
            return color;
        }

        function setPxInfo(imgdata,x,y,color){
            var data = imgdata.data;
            var w = imgdata.width;
            var h = imgdata.height;
            data[(y*w+x)*4]=color[0];
            data[(y*w+x)*4+1]=color[1];
            data[(y*w+x)*4+2]=color[2];
            data[(y*w+x)*4+3]=color[3];
        }
    }
</script>
</body>
</html>